package com.gitee.huanminabc.utils_tools.zk;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Dubbo Zookeeper 工具类
 * 基于 ZookeeperUtil 的包装器，自动从 Dubbo 配置中读取 Zookeeper 地址
 *
 * @author sby
 * @since 1.0.0
 */
@Setter
@Getter
@Slf4j
@Component
@ConditionalOnProperty(prefix = "dubbo.registry", name = "address")
public class DubboZookeeperUtil extends ZookeeperUtil {

    /**
     *  获取 Zookeeper 地址
     *  手动设置 Zookeeper 地址
     */
    @Value("${dubbo.registry.address:}")
    private String zookeeperAddress;

    /**
     *  获取注册中心超时时间
     *  手动设置注册中心超时时间
     *

     */
    @Value("${dubbo.registry.timeout:30000}")
    private int registryTimeout;
    
    /**
     * 初始化方法，从配置中获取 Zookeeper 地址并连接
     */
    @PostConstruct
    public void init() {
        try {
            if (zookeeperAddress != null && !zookeeperAddress.trim().isEmpty()) {
                log.info("从 Dubbo 配置中获取到 Zookeeper 地址: {}", zookeeperAddress);
                this.setSessionTimeout(registryTimeout);
                
                // 尝试连接
                if (connect()) {
                    log.info("成功连接到 Zookeeper: {}", zookeeperAddress);
                } else {
                    log.error("连接 Zookeeper 失败: {}", zookeeperAddress);
                }
            } else {
                log.warn("未找到 Dubbo Zookeeper 配置，请检查 dubbo.registry.address 配置");
            }
        } catch (Exception e) {
            log.error("初始化 Zookeeper 连接失败", e);
        }
    }

}
